from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.response import Response

from .models import Absent,AbsentType,AbsentStatusChoices
from rest_framework import  mixins
from .serializers import AbsentSerializer, AbsentTypeSerializer
from rest_framework.views import APIView
from .utils import get_responder
from apps.oaauth.serializers import UserSerializer
# Create your views here.

'''
1、发起考勤 (create)
2、处理考勤 (update)
3、查看自己的考勤列表 (lsit?who=my)
4、查看下属的考勤列表 (list?who=sub)
'''
class AbsentViewSet(mixins.CreateModelMixin,
                   mixins.UpdateModelMixin,
                   mixins.ListModelMixin,
                   viewsets.GenericViewSet):
    queryset = Absent.objects.all()  ## 返回 Absent 所有实例
    print(f"queryset is {queryset} ")
    serializer_class = AbsentSerializer

    ## 重新序列化中的方法 允许修改部分数据
    def update(self, request, *args, **kwargs):
        kwargs['partial'] = True
        return super().update(request, *args, **kwargs)


## 根号请求参数 去响应查看自己的list  还是下属 sub 的 list
    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        who  = request.query_params.get('who')  ##获取 url 后面携带的参数
        if who and who == 'sub':
            results = queryset.filter(responder=request.user)  ## 有审批人的就是下属的
        else:
            results = queryset.filter(requester=request.user)  ##  看自己的

        ## 分页
        page = self.paginate_queryset(results)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = AbsentSerializer(results, many=True)
        return Response(data=serializer.data)


##获取请假类型
class AbsentTpyeView(APIView):
    def get(self, request):
        types = AbsentType.objects.all()
        serializer = AbsentTypeSerializer(types, many=True)
        return Response(data=serializer.data)

## 显示审批者
class ResponderView(APIView):
    def get(self,request):
        ## 获取审批者
        responder = get_responder(request)
        serializer = UserSerializer(responder)
        return Response(data=serializer.data)
